import React, { useState, useEffect, useRef } from 'react';
import { GridContent } from '@ant-design/pro-layout';
import { Menu, Form, Button, Dropdown, message, Icon, Switch} from 'antd';
import styles from './style.less';
import { FormComponentProps } from 'antd/lib/form';
import { queryRule } from './service';
import { bdExec } from '@/helpers/RequestHelper';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { DownOutlined } from '@ant-design/icons';
import moment from 'moment';
import { FormValueType } from './components/ConfigForm';
import ConfigForm from './components/ConfigForm';
import { addRule, updateRule, removeRule } from './service';
import * as tsxHelper from '@/helpers/TsxHelper';

const { Item } = Menu;
interface ConfigListProps extends FormComponentProps {}

const handleAdd = async (fields: FormValueType) => {
  return bdExec({fn: addRule, args: fields, successMsg: '添加成功',failMsg: '添加失败请重试！'});
};

const handleUpdate = async (fields: FormValueType) => {
  return bdExec({fn: updateRule, args: fields, successMsg: '更新成功',failMsg: '更新失败请重试！'});
};
const handleUpdateItem = async (fields: any) => {
  return bdExec({fn: updateRule, args: fields, successMsg: '更新成功',failMsg: '更新失败请重试！'});
};
const handleRemove = async (selectedRows: any[]) => {
  if (!selectedRows) return true;
  const ids:any = selectedRows.toString();
  return bdExec({fn: removeRule, args: {ids}, successMsg: '删除成功，即将刷新',failMsg: '删除失败，请重试！', hasLoading: false});
};

const ConfigList: React.FC<ConfigListProps> = (props) => {

  let main: HTMLDivElement | undefined  | any = undefined;
  const actionRef = useRef<ActionType>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const [selectIndex, setSelectIndex] = useState<string>('');
  const [isExpand, setIsExpand] = useState<boolean>(false);
  const [oneLevelIds, setOneLevelIds] = useState<any[]>([]);
  const [expandedRowKeys, setExpandedRowKeys] = useState<any[]>([]);
  const [mode, setMode] = useState<any>('inline');
  const [rowKeys, setRowKeys] = useState<string[]|number[]>([]);
  const [isUpdate, setIsUpdate] = useState<boolean>(false);
  const [radioType, setRadioType] = useState<string | 'url'| 'app'>('url');
  const [picture, setPicture] = useState<any[]>([]);
  const [stateData, setStateData] = useState<any>({common:{}});

  useEffect(() => {
    window.addEventListener('resize', resize);
    resize();
    initData();
    return () => window.removeEventListener('resize', resize);
  }, []);
  
  const columns:ProColumns<any>[] = [
    {
      title: '变量名',
      dataIndex: 'name',
    },
    {
      title: '变量标识',
      dataIndex: 'nickname',
      hideInSearch: true,
    },
    {
      title: '链接',
      dataIndex: 'link_href',
      hideInSearch: true,
    },
    // {
    //   title: '变量值',
    //   dataIndex: 'content',
    //   // hideInSearch: true,
    // },
    {
      title: '是否启用',
      dataIndex: 'is_enable',
      hideInSearch: true,
      render: (_, record) => (
        <Switch checked={record.is_enable} onChange={async () => {
          let s = await handleUpdateItem({id: record.id, is_enable: !record.is_enable});
          s && actionRef.current?.reload();
        }} />
      )
    },
    {
      title: '排序',
      dataIndex: 'rank_num',
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      sorter: true,
      hideInSearch: true,
      render: (val:any) => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_: any, record: React.SetStateAction<any>) => (
        <>
          <a
            onClick={() => {
              handleModalVisible(true);
              initValuesData(record);
            }}
          >
            编辑
          </a>
        </>
      ),
    },
  ];

  const initData = (params?:any) => {
    const args:any = {};
    params && params.selectIndex != '' && (args.config_group_id = params.selectIndex);

    return bdExec({
      fn: queryRule, 
      args,
      failMsg: '请求数据失败',
      hasCallBack: true,
      hasLoading: false,
    }).then((res:any) => {
      if(res.execStatus){
        // todo 注意： 如果state为一个对象时，这个时候需要进行合并的。 
        setStateData(res.data)
        params && setSelectIndex(params.selectIndex == '' ? 
        res.data.common.sideBarList[0].id.toString() : params.selectIndex);
        // 获取所有一级分类的id
        let ids:any = [];
        res.data.listData.data.forEach((v:any) => {
          ids.push(v.id);
        })
        setOneLevelIds(ids);
        return res.data.listData;
      }
    })
  }

  const initValuesData = (record:any) => {
    setIsUpdate(true);
    setStepFormValues(record);
    setRadioType(record.type);
    (record.file_url && typeof record.file_url != 'undefined') && buildPicture(record.file_url);
  }
  
  const getMenu = () => {
    const menuMap = stateData.common.sideBarList || [];
    return menuMap.map((item:any) => <Item key={`${item.id}`}>{item.name}</Item>);
  };

  const getRightTitle = () => {
    const menuMap = stateData.common.sideBarList || [];
    const selectItem = menuMap.filter((item:any) => item.id.toString() === selectIndex);
    return selectItem.length > 0 ? selectItem[0].name : '';
  };

  const selectKey = (key: string) => {
    setSelectIndex(key);
  };

  const resize = () => {
    if (!main) {
      return;
    }
    requestAnimationFrame(() => {
      if (!main) {
        return;
      }
      let mode: 'inline' | 'horizontal' = 'inline';
      const { offsetWidth } = main;
      if (main.offsetWidth < 641 && offsetWidth > 400) {
        mode = 'horizontal';
      }
      if (window.innerWidth < 768 && offsetWidth > 400) {
        mode = 'horizontal';
      }
      setMode(mode);
    });
  };

  const handleChangeType = (value:any) => {
    setRadioType(value)
  }

  const handleSetPicture = (value:any) => {
    setPicture(value)
  }

  const buildPicture = (url:any) => {
    if(url){
      setPicture([{
        uid: '-1',
        name: url.split('/').pop(),
        status: 'done',
        url: url,
        thumbUrl: url,
      }]);
    }
  }

  const handleExpandAll = (isExpand:boolean) => {
    if(!isExpand){
      let allIds:any[] = [];
      stateData.listData.data.forEach((item:any) => {
        if(item.childrenIds && item.childrenIds.length > 0){
          allIds = [item.id, ...allIds, ...item.childrenIds];
        }
      })
      setExpandedRowKeys(allIds);
      setIsExpand(true);
    }else{
      setExpandedRowKeys([]);
      setIsExpand(false);
    }
  }

  const handleExpandedRowsChange = (expandedRows:string[]|number[]) => {
    setExpandedRowKeys(expandedRows);
    let expandedStatus = false;
    oneLevelIds.forEach((id:number) => {
      // 如果有一个一级id存在于expandedRows中，就说明是展开的状态，isExpand该为true;
      if(expandedRows.toString().indexOf(id.toString()) > -1){
        expandedStatus = true;
      }
    })
    // 设置当前分类是否为展开状态： true为展开
    setIsExpand(expandedStatus);

  }

  const handleOnSubmit = (value:FormValueType) => {
    return new Promise((resolve, reject) => {
      let s = isUpdate ? handleUpdate(value) : handleAdd(value);
      resolve(s);
    }).then( status => {
      if(status){
        handleModalVisible(false);
        setPicture([]);
        setRadioType('url');
        if (actionRef.current) {
          actionRef.current.reload();
        }
      }
      return status; // 返回执行结果:boolean, 子组件接收此值来重置数据
    })
  }

  return (
    <GridContent>
      <div
        className={styles.main}
        ref={ref => {
          if (ref) {
            main = ref;
          }
        }}
      >
        <div className={styles.leftMenu}>
          <Menu
            mode={mode}
            selectedKeys={[selectIndex]}
            onClick={({ key }) => selectKey(key)}
          >
            {getMenu()}
          </Menu>
        </div>
        <div className={styles.right}>
          <ProTable<any>
            headerTitle={getRightTitle()}
            actionRef={actionRef}
            rowKey="key"
            search={false}
            pagination={{
              showSizeChanger: true,
            }}
            toolBarRender={(action, { selectedRowKeys, selectedRows }) => [
              <Button icon={isExpand ? 'minus':'plus'} 
                onClick={() => {
                  handleExpandAll(isExpand);
                }}
              >
                {isExpand ? '收起':'展开'}
              </Button>,
              <Button icon={'plus'} type="primary" 
                onClick={() => {
                  handleModalVisible(true)
                  setIsUpdate(false);
                }}
              >
                新建
              </Button>,
              selectedRowKeys && selectedRowKeys.length > 0 && (
                <Dropdown
                  overlay={
                    <Menu
                      onClick={async e => {
                        if (e.key === 'remove') {
                          tsxHelper.showDeleteConfirm(
                            'danger',
                            handleRemove,
                            selectedRowKeys,
                            () => {
                              setRowKeys([]);
                              action.reload();
                            }
                          )
                        }
                      }}
                      selectedKeys={[]}
                    >
                      <Menu.Item key="remove">批量删除</Menu.Item>
                    </Menu>
                  }
                >
                  <Button>
                    批量操作 <DownOutlined />
                  </Button>
                </Dropdown>
              ),
            ]}
            tableAlertRender={(selectedRowKeys, selectedRows) => (
              <div>
                已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项&nbsp;&nbsp;
              </div>
            )}
            request={(params) => initData(params)}
            // 这个参数会自动注入到params中去，如果selectIndex修改， 还会触发reload()
            params={{
              selectIndex,
            }}
            columns={columns}
            rowSelection={{
              onChange: (selectedRowKeys, selectedRows) => {
                setRowKeys(selectedRowKeys);
              },
              selectedRowKeys: rowKeys,
            }}
            defaultExpandAllRows={true}
            expandRowByClick={false}
            expandedRowKeys={expandedRowKeys}
            onExpand={(expanded, record) => {
              console.log(expanded, record)
            }}
            onExpandedRowsChange={(expandedRows) => handleExpandedRowsChange(expandedRows)}
          />
          <ConfigForm
            onSubmit={(value) => handleOnSubmit(value)}
            onCancel={() => {
              handleModalVisible(false);
              setPicture([]);;
            }}
            modalVisible={createModalVisible}
            handleChangeType={handleChangeType}
            handleSetPicture={handleSetPicture}
            values={stepFormValues}
            otherValues={{
              common: stateData.common || {},
              selectIndex,
              isUpdate,
              radioType,
              picture,
            }}
            changeParamType={()=>{}}
          />
        </div>
      </div>
    </GridContent>
  );
}

export default Form.create<ConfigListProps>()(ConfigList);

